<?php
class Admin_UserController extends Zend_Controller_Action
{
	protected $_user;
	protected $_roles;

	public function init() {
		$this->_helper->layout()->setLayout('admin');

		$this->_user  = new Admin_Model_User();
		$this->_roles = new Admin_Model_Roles();
	}

	public function indexAction() {
		$this->view->users = $this->_user->getAllUsers();
	}

	public function addUserAction() {			
		if ($this->getRequest()->isPost()) {
			$post = $this->getRequest()->getPost();

			$password = $this->_user->generatePassword();
			$userId = $this->_user->addUser(
				array(
					'email'    => $post['user_email'],
					'password' => md5($password)
				)
			);
			$this->_user->bindUserToRole($userId, $post['role_id']);
			$this->_user->sendEmail($post['user_email'], $password);

			$this->_helper->redirector('index', 'user', 'admin');
		}

		$this->view->roles = $this->_roles->getAllRoles();
	}

	public function editUserAction() {
		$userId = $this->_getParam('user');

		if ($this->getRequest()->isPost()) {
			$post = $this->getRequest()->getPost();
			
			$this->_user->updateUser(
				$userId,
				array(
					'email' => $post['user_email']					
				)
			);
			$this->_user->deleteBindUserRole($userId);
			$this->_user->bindUserToRole($userId, $post['role_id']);		

			$this->_helper->redirector('index', 'user', 'admin');
		}

		$this->view->user  = $this->_user->getUser($userId);
		$this->view->roles = $this->_roles->getAllRoles();		
	}

	public function deleteUserAction() {
		$userId = $this->_getParam('user');
		$this->_user->deleteUser($userId);
		$this->_user->deleteBindUserRole($userId);

		$this->_helper->redirector('index', 'user', 'admin');
	}
}